const { app, BrowserWindow, dialog, ipcMain, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const TaskManager = require('./task-manager');

let mainWindow;
let config = {};
let taskManager = new TaskManager();

// 加载配置文件
function loadConfig() {
  try {
    const configPath = path.join(__dirname, 'app-config.json');
    if (fs.existsSync(configPath)) {
      config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    }
    
    // 初始化任务管理器
    taskManager.loadRoles();
    taskManager.setConfig(config);
    
    // 加载任务状态
    if (config.sandboxPath) {
      const taskStatePath = path.join(config.sandboxPath, '.synapse-tasks.json');
      taskManager.loadFromFile(taskStatePath);
    }
  } catch (error) {
    console.error('加载配置文件失败:', error);
  }
}

// 保存配置文件
function saveConfig() {
  try {
    const configPath = path.join(__dirname, 'app-config.json');
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    
    // 保存任务状态
    if (config.sandboxPath) {
      const taskStatePath = path.join(config.sandboxPath, '.synapse-tasks.json');
      taskManager.saveToFile(taskStatePath);
    }
  } catch (error) {
    console.error('保存配置文件失败:', error);
  }
}

// AI模型调用
async function callAIModel(role, message) {
  try {
    const aiConfig = config.ai?.model;
    if (!aiConfig) {
      throw new Error('AI配置未设置');
    }

    const response = await fetch(aiConfig.url + '/api/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: aiConfig.name,
        prompt: `你是一个${role}。用户说："${message}"。请以${role}的身份回复，并分析是否需要创建任务。如果需要创建任务，请以JSON格式返回：{"tasks": [{"title": "任务标题", "description": "任务描述", "priority": "high/medium/low", "assignee": "角色名称"}]}。如果不需要创建任务，请直接回复。`,
        stream: false
      })
    });

    if (!response.ok) {
      throw new Error(`AI服务响应错误: ${response.status}`);
    }

    const data = await response.json();
    return data.response;
  } catch (error) {
    console.error('AI模型调用失败:', error);
    throw error;
  }
}

// 创建主窗口
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');
  
  if (process.argv.includes('--dev')) {
    mainWindow.webContents.openDevTools();
  }
}

// 创建应用菜单
function createMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '新建项目',
          accelerator: 'CmdOrCtrl+N',
          click: async () => {
            await newProject();
          }
        },
        {
          label: '打开项目',
          accelerator: 'CmdOrCtrl+O',
          click: async () => {
            await openProject();
          }
        },
        {
          label: '保存项目',
          accelerator: 'CmdOrCtrl+S',
          click: async () => {
            await saveProject();
          }
        },
        {
          label: '关闭项目',
          accelerator: 'CmdOrCtrl+W',
          click: async () => {
            await closeProject();
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { role: 'undo' },
        { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' },
        { role: 'copy' },
        { role: 'paste' },
        { role: 'selectall' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { role: 'reload' },
        { role: 'forceReload' },
        { role: 'toggleDevTools' },
        { type: 'separator' },
        { role: 'resetZoom' },
        { role: 'zoomIn' },
        { role: 'zoomOut' },
        { type: 'separator' },
        { role: 'togglefullscreen' }
      ]
    },
    {
      label: '项目',
      submenu: [
        {
          label: '项目设置',
          accelerator: 'CmdOrCtrl+,',
          click: () => {
            openSettings();
          }
        },
        {
          label: '刷新文件',
          accelerator: 'F5',
          click: () => {
            mainWindow.webContents.send('refresh-files');
          }
        },
        { type: 'separator' },
        {
          label: '导出项目',
          click: async () => {
            await exportProject();
          }
        }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于 Synapse Team',
          click: () => {
            showAbout();
          }
        },
        {
          label: '检查更新',
          click: () => {
            checkForUpdates();
          }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// 新建项目
async function newProject() {
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: '选择新项目文件夹',
      properties: ['createDirectory', 'openDirectory']
    });

    if (!result.canceled && result.filePaths.length > 0) {
      const projectPath = result.filePaths[0];
      
      // 创建项目结构
      const projectStructure = {
        'src': {},
        'docs': {},
        'tests': {},
        'package.json': JSON.stringify({
          name: path.basename(projectPath),
          version: '1.0.0',
          description: 'Synapse Team 项目'
        }, null, 2),
        'README.md': `# ${path.basename(projectPath)}\n\n由 Synapse Team 创建的项目。`
      };

      await createProjectStructure(projectPath, projectStructure);
      
      // 更新配置
      config.sandboxPath = projectPath;
      config.currentProject = {
        name: path.basename(projectPath),
        path: projectPath,
        createdAt: new Date().toISOString()
      };
      saveConfig();

      // 通知渲染进程
      mainWindow.webContents.send('project-opened', {
        name: path.basename(projectPath),
        path: projectPath
      });

      dialog.showMessageBox(mainWindow, {
        type: 'info',
        title: '项目创建成功',
        message: `项目 "${path.basename(projectPath)}" 已创建并打开。`
      });
    }
  } catch (error) {
    console.error('新建项目失败:', error);
    dialog.showErrorBox('错误', `新建项目失败: ${error.message}`);
  }
}

// 创建项目结构
async function createProjectStructure(basePath, structure) {
  for (const [name, content] of Object.entries(structure)) {
    const fullPath = path.join(basePath, name);
    
    if (typeof content === 'object') {
      // 创建目录
      if (!fs.existsSync(fullPath)) {
        fs.mkdirSync(fullPath, { recursive: true });
      }
    } else {
      // 创建文件
      fs.writeFileSync(fullPath, content);
    }
  }
}

// 打开项目
async function openProject() {
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: '选择项目文件夹',
      properties: ['openDirectory']
    });

    if (!result.canceled && result.filePaths.length > 0) {
      const projectPath = result.filePaths[0];
      
      // 更新配置
      config.sandboxPath = projectPath;
      config.currentProject = {
        name: path.basename(projectPath),
        path: projectPath,
        openedAt: new Date().toISOString()
      };
      saveConfig();

      // 通知渲染进程
      mainWindow.webContents.send('project-opened', {
        name: path.basename(projectPath),
        path: projectPath
      });

      dialog.showMessageBox(mainWindow, {
        type: 'info',
        title: '项目打开成功',
        message: `项目 "${path.basename(projectPath)}" 已打开。`
      });
    }
  } catch (error) {
    console.error('打开项目失败:', error);
    dialog.showErrorBox('错误', `打开项目失败: ${error.message}`);
  }
}

// 保存项目
async function saveProject() {
  try {
    if (!config.currentProject) {
      dialog.showMessageBox(mainWindow, {
        type: 'warning',
        title: '无项目',
        message: '请先打开一个项目。'
      });
      return;
    }

    // 保存项目状态
    const projectState = {
      lastSaved: new Date().toISOString(),
      version: '1.0.0'
    };

    const statePath = path.join(config.currentProject.path, '.synapse-state.json');
    fs.writeFileSync(statePath, JSON.stringify(projectState, null, 2));

    // 通知渲染进程
    mainWindow.webContents.send('project-saved');

    dialog.showMessageBox(mainWindow, {
      type: 'info',
      title: '保存成功',
      message: '项目状态已保存。'
    });
  } catch (error) {
    console.error('保存项目失败:', error);
    dialog.showErrorBox('错误', `保存项目失败: ${error.message}`);
  }
}

// 关闭项目
async function closeProject() {
  try {
    if (!config.currentProject) {
      dialog.showMessageBox(mainWindow, {
        type: 'warning',
        title: '无项目',
        message: '当前没有打开的项目。'
      });
      return;
    }

    // 检查是否有未保存的更改
    const hasUnsavedChanges = await checkUnsavedChanges();
    
    if (hasUnsavedChanges) {
      const result = await dialog.showMessageBox(mainWindow, {
        type: 'question',
        title: '未保存的更改',
        message: '项目有未保存的更改，是否保存？',
        buttons: ['保存', '不保存', '取消'],
        defaultId: 0
      });

      if (result.response === 0) {
        await saveProject();
      } else if (result.response === 2) {
        return; // 取消
      }
    }

    // 清除项目配置
    config.sandboxPath = '';
    config.currentProject = null;
    saveConfig();

    // 通知渲染进程
    mainWindow.webContents.send('project-closed');

    dialog.showMessageBox(mainWindow, {
      type: 'info',
      title: '项目已关闭',
      message: '项目已关闭。'
    });
  } catch (error) {
    console.error('关闭项目失败:', error);
    dialog.showErrorBox('错误', `关闭项目失败: ${error.message}`);
  }
}

// 检查未保存的更改
async function checkUnsavedChanges() {
  // 这里可以实现更复杂的未保存更改检测逻辑
  // 目前返回 false，表示没有未保存的更改
  return false;
}

// 打开设置
function openSettings() {
  const settingsWindow = new BrowserWindow({
    width: 800,
    height: 600,
    parent: mainWindow,
    modal: true,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  settingsWindow.loadFile('settings.html');
  settingsWindow.setMenu(null);
}

// 导出项目
async function exportProject() {
  try {
    if (!config.currentProject) {
      dialog.showMessageBox(mainWindow, {
        type: 'warning',
        title: '无项目',
        message: '请先打开一个项目。'
      });
      return;
    }

    const result = await dialog.showSaveDialog(mainWindow, {
      title: '导出项目',
      defaultPath: `${config.currentProject.name}.zip`,
      filters: [
        { name: 'ZIP文件', extensions: ['zip'] }
      ]
    });

    if (!result.canceled) {
      // 这里可以实现项目导出逻辑
      dialog.showMessageBox(mainWindow, {
        type: 'info',
        title: '导出成功',
        message: '项目导出功能将在后续版本中实现。'
      });
    }
  } catch (error) {
    console.error('导出项目失败:', error);
    dialog.showErrorBox('错误', `导出项目失败: ${error.message}`);
  }
}

// 显示关于信息
function showAbout() {
  dialog.showMessageBox(mainWindow, {
    type: 'info',
    title: '关于 Synapse Team',
    message: 'Synapse Team v1.0.0\n\nAI驱动的虚拟软件开发团队\n\n基于 Electron 和 Ollama 构建',
    detail: '一个革命性的AI协作平台，让编程变得像对话一样简单。'
  });
}

// 检查更新
function checkForUpdates() {
  dialog.showMessageBox(mainWindow, {
    type: 'info',
    title: '检查更新',
    message: '当前已是最新版本。\n\n更新检查功能将在后续版本中实现。'
  });
}

// 选择文件夹对话框
ipcMain.handle('select-folder', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  
  if (!result.canceled && result.filePaths.length > 0) {
    config.sandboxPath = result.filePaths[0];
    saveConfig();
    return result.filePaths[0];
  }
  return null;
});

// 获取配置
ipcMain.handle('get-config', () => {
  return config;
});

// 更新配置
ipcMain.handle('update-config', (event, newConfig) => {
  config = { ...config, ...newConfig };
  saveConfig();
  return true;
});

// 验证AI模型连接
ipcMain.handle('test-ai-connection', async (event, modelConfig) => {
  try {
    const response = await fetch(modelConfig.url + '/api/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: modelConfig.name,
        prompt: 'test',
        stream: false
      })
    });
    
    return response.ok;
  } catch (error) {
    console.error('AI连接测试失败:', error);
    return false;
  }
});

// AI聊天交互
ipcMain.handle('chat-with-ai', async (event, role, message) => {
  try {
    // 如果是项目经理，尝试解析任务
    if (role === 'project_manager') {
      try {
        const taskData = await taskManager.parseUserInput(message, callAIModel);
        const newTasks = taskManager.createTasks(taskData);
        
        return {
          type: 'task_creation',
          message: taskData.analysis || '已创建任务列表',
          tasks: newTasks,
          analysis: taskData.analysis
        };
      } catch (parseError) {
        // 如果解析失败，返回普通消息
        const response = await callAIModel(role, message);
        return {
          type: 'message',
          message: response
        };
      }
    } else {
      const response = await callAIModel(role, message);
      return {
        type: 'message',
        message: response
      };
    }
  } catch (error) {
    throw new Error(`AI聊天失败: ${error.message}`);
  }
});

// 文件上传处理
ipcMain.handle('upload-file', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [
      { name: '图片文件', extensions: ['png', 'jpg', 'jpeg'] },
      { name: 'JSON文件', extensions: ['json'] },
      { name: '所有文件', extensions: ['*'] }
    ]
  });
  
  if (!result.canceled && result.filePaths.length > 0) {
    const filePath = result.filePaths[0];
    const fileName = path.basename(filePath);
    const fileContent = fs.readFileSync(filePath);
    
    return {
      name: fileName,
      path: filePath,
      size: fileContent.length,
      type: path.extname(filePath).toLowerCase()
    };
  }
  return null;
});

// 读取文件内容
ipcMain.handle('read-file', (event, filePath) => {
  try {
    const fullPath = path.join(config.sandboxPath || '', filePath);
    if (!fullPath.startsWith(config.sandboxPath)) {
      throw new Error('访问路径超出沙盒范围');
    }
    
    if (!fs.existsSync(fullPath)) {
      throw new Error('文件不存在');
    }
    
    const stats = fs.statSync(fullPath);
    if (stats.isDirectory()) {
      const files = fs.readdirSync(fullPath);
      return {
        type: 'directory',
        content: files,
        path: filePath
      };
    } else {
      const content = fs.readFileSync(fullPath, 'utf8');
      const ext = path.extname(fullPath).toLowerCase();
      
      return {
        type: 'file',
        content: content,
        path: filePath,
        extension: ext,
        size: stats.size
      };
    }
  } catch (error) {
    throw new Error(`读取文件失败: ${error.message}`);
  }
});

// 写入文件内容
ipcMain.handle('write-file', (event, filePath, content) => {
  try {
    const fullPath = path.join(config.sandboxPath || '', filePath);
    if (!fullPath.startsWith(config.sandboxPath)) {
      throw new Error('访问路径超出沙盒范围');
    }
    
    // 确保目录存在
    const dir = path.dirname(fullPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
    fs.writeFileSync(fullPath, content);
    return true;
  } catch (error) {
    throw new Error(`写入文件失败: ${error.message}`);
  }
});

// 获取沙盒文件列表
ipcMain.handle('get-sandbox-files', () => {
  try {
    if (!config.sandboxPath || !fs.existsSync(config.sandboxPath)) {
      return [];
    }
    
    function scanDirectory(dir, basePath = '') {
      const items = [];
      const files = fs.readdirSync(dir);
      
      for (const file of files) {
        const fullPath = path.join(dir, file);
        const relativePath = path.join(basePath, file);
        const stats = fs.statSync(fullPath);
        
        if (stats.isDirectory()) {
          items.push({
            name: file,
            path: relativePath,
            type: 'directory',
            children: scanDirectory(fullPath, relativePath)
          });
        } else {
          items.push({
            name: file,
            path: relativePath,
            type: 'file',
            size: stats.size,
            extension: path.extname(file).toLowerCase()
          });
        }
      }
      
      return items;
    }
    
    return scanDirectory(config.sandboxPath);
  } catch (error) {
    console.error('获取沙盒文件列表失败:', error);
    return [];
  }
});

// 沙盒文件操作
ipcMain.handle('sandbox-read-file', (event, filePath) => {
  try {
    const fullPath = path.join(config.sandboxPath || '', filePath);
    if (!fullPath.startsWith(config.sandboxPath)) {
      throw new Error('访问路径超出沙盒范围');
    }
    return fs.readFileSync(fullPath, 'utf8');
  } catch (error) {
    throw new Error(`读取文件失败: ${error.message}`);
  }
});

ipcMain.handle('sandbox-write-file', (event, filePath, content) => {
  try {
    const fullPath = path.join(config.sandboxPath || '', filePath);
    if (!fullPath.startsWith(config.sandboxPath)) {
      throw new Error('访问路径超出沙盒范围');
    }
    fs.writeFileSync(fullPath, content);
    return true;
  } catch (error) {
    throw new Error(`写入文件失败: ${error.message}`);
  }
});

// 任务管理相关IPC处理
ipcMain.handle('get-task-status', () => {
  return taskManager.getTaskStatus();
});

ipcMain.handle('get-gantt-data', () => {
  return taskManager.getGanttData();
});

ipcMain.handle('start-task', async (event, taskId) => {
  try {
    const result = await taskManager.startTask(taskId, callAIModel);
    saveConfig(); // 保存任务状态
    return result;
  } catch (error) {
    throw new Error(`启动任务失败: ${error.message}`);
  }
});

ipcMain.handle('execute-tasks-parallel', async (event, taskIds, maxConcurrent = 3) => {
  try {
    const results = await taskManager.executeTasksParallel(taskIds, callAIModel, maxConcurrent);
    saveConfig(); // 保存任务状态
    return results;
  } catch (error) {
    throw new Error(`并行执行任务失败: ${error.message}`);
  }
});

ipcMain.handle('get-executable-tasks', () => {
  return taskManager.getExecutableTasks();
});

ipcMain.handle('reset-tasks', () => {
  taskManager.reset();
  saveConfig();
  return true;
});

ipcMain.handle('get-roles', () => {
  return taskManager.roles;
});

app.whenReady().then(() => {
  loadConfig();
  createWindow();
  createMenu();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
